package com.hunt.app.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hunt.model.dto.UserLevel;
import com.hunt.service.UserLevelService;
import com.hunt.util.Result;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class AppFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(AppFilter.class);

    @Autowired
    private JedisPool jedisPool;
@Autowired
private UserLevelService userLevelService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        XmlWebApplicationContext cxt = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(servletContext);
        if(cxt != null && cxt.getBean("jedisTemplate") != null && jedisPool == null) {
            jedisPool = (JedisPool) cxt.getBean("jedisTemplate");
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String url = req.getRequestURL().toString();
        //尊享手机用户过滤器
        if (url.contains("/ddx/app_findDDXRankingBySortNumber")
                || url.contains("/northFund/app_getAllNorthBoundStocks")
                || url.contains("/company/app_getCompanyPost")
        ){
            String token = req.getHeader("token");
            if (token == null || token.equals("")){
                resp.sendRedirect(req.getContextPath()+"/system/app_token_check_failed");
                return;
            }
            Jedis jedis = null;
            try {
                Claims claims = JWTTokenUtil.parseToken(token);
                String userId = claims.get("userId").toString();
                jedis = jedisPool.getResource();
                String redisToken = jedis.hmget("app_token_check", userId).get(0);
                if (redisToken == null || redisToken.equals("")){
                    resp.sendRedirect(req.getContextPath()+"/system/app_token_check_failed");
                    return;
                }
                if (token.equals(redisToken)){
                    String userLevel = claims.get("userLevel").toString();
                    UserLevel ul=userLevelService.selectByUserLevel(userLevel);
                    if (ul.getDddx()==0&&url.contains("/ddx/app_findDDXRankingBySortNumber")){
                        resp.sendRedirect(req.getContextPath()+"/system/app_token_check_unauthorized");
                    }
                    else  if (ul.getBxzj()==0&&url.contains("/northFund/app_getAllNorthBoundStocks")){
                        resp.sendRedirect(req.getContextPath()+"/system/app_token_check_unauthorized");
                    }
                    else{
                        chain.doFilter(req,resp);
                    }
                }else{
                    resp.sendRedirect(req.getContextPath()+"/system/app_token_check_failed");
                }
            }catch (Exception e){
                resp.sendRedirect(req.getContextPath()+"/system/app_token_check_failed");
            }finally {
                if (jedis != null){
                    jedis.close();
                }
            }
        }else{
            chain.doFilter(req,resp);
        }
    }

    @Override
    public void destroy() {

    }
}
